package com.example.eeuse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.example.eeuse.model.KibanaBaseReq;
import com.example.eeuse.util.KibanaUtil;

import java.io.File;
import java.util.*;

public class KibanaSample {
    public static void main(String[] args) throws Exception {
        String dateStr="2023-12-01";
        String dep="CAN";
        String arr="PKX";
        writeSampleByDate(dateStr,dep,arr);
    }

    public static void writeSampleByDate(String dateStr,String dep,String arr) throws Exception {
        String indexName="shopping_log_part_sample-*";
        Date beginDate=DateUtil.parse(dateStr,"yyyy-MM-dd");
        Calendar searchTime = Calendar.getInstance();
        searchTime.setTime(beginDate);
        //searchTime.add(Calendar.HOUR,-8);
        for(int i=0;i<=24;i++) {
            String beginTime=DateUtil.format(searchTime.getTime(), "yyyy-MM-dd'T'HH:mm:ss");
            searchTime.add(Calendar.HOUR, 1);
            String endTime=DateUtil.format(searchTime.getTime(), "yyyy-MM-dd'T'HH:mm:ss");
            //创建post请求
            HttpRequest post = KibanaUtil.createPost(indexName);

            List<Object> list=new ArrayList<>();
            list.add(new KibanaBaseReq.Must("ARR.keyword",arr));
            list.add(new KibanaBaseReq.Must("DEP.keyword",dep));
            list.add(new KibanaBaseReq.Must("SAMPLE_NODE.keyword","SAMPLE_RESPONSE"));
            list.add(new KibanaBaseReq.Range("@timestamp",beginTime,endTime));
            KibanaBaseReq kibanaBaseReq=KibanaUtil.createReq(100,list);

            String body =JSONUtil.toJsonStr(kibanaBaseReq);
            //设置请求体
            post.body(body);
            //请求
            HttpResponse execute = post.execute();
            //获得响应结果
            String json = execute.body();
//            System.out.println(json);
            //转成map
            Map map = JSONUtil.toBean(json, Map.class);
            int total=(int)((Map)((Map)map.get("hits")).get("total")).get("value");
            if(total>0)
            {
                List<Map> itemList=(List<Map>)((Map)map.get("hits")).get("hits");
                for(Map item:itemList)
                {
                    Map object= (Map) item.get("_source");
                    String traceId=(String) object.get("TRACE_ID");
                    String timestamp=(String) object.get("@timestamp");
                    String data=(String) object.get("DATA");
                    String date=(String) object.get("DATE");
                    String _id=(String) item.get("_id");
                    String localTime=(String) object.get("TIMESTAMP");
                    if(!data.startsWith("Shopping")) {
                        boolean writeFare=writeSampleById(traceId,dateStr,dep,arr,"SAMPLE_FARE");
                        if(writeFare)
                        {
                            writeSampleById(traceId,dateStr,dep,arr,"SAMPLE_REQUEST");
                            writeSampleById(traceId,dateStr,dep,arr,"SAMPLE_IBE");
                            String fileName=dep + "_" + arr + "_"+date+"_" +localTime.replace(" ","T").replaceAll(":","M")+"_"+ traceId + ".txt";
                            String filePath="D:\\test\\SAMPLE\\SAMPLE_RESPONSE\\";
                            FileUtil.mkdir(filePath);
                            FileUtil.writeBytes(data.getBytes(), filePath + fileName);
                        }
                    }
                }
                System.out.println(beginTime+","+total);
            }
        }
    }

    public static boolean writeSampleById(String tradeId,String dateStr,String dep,String arr,String sampleType) throws Exception {
        String indexName="shopping_log_part_sample-*";
        boolean result=false;
        HttpRequest post = KibanaUtil.createPost(indexName);
        String body =
                "{\n" +
                        "  \"size\": 10, \n" +
                        "  \"query\": {\n" +
                        "    \"bool\": {\n" +
                        "      \"must\": [\n" +
                        "          {\n" +
                        "            \"match\": {\n" +
                        "            \"TRACE_ID.keyword\": \""+tradeId+"\"\n" +
                        "            \n" +
                        "            }\n" +
                        "          },\n" +
                        "          {\n" +
                        "            \"match\": {\n" +
                        "            \"SAMPLE_NODE.keyword\": \""+sampleType+"\"\n" +
                        "            \n" +
                        "            }\n" +
                        "          }\n" +
                        "      ]\n" +
                        "      \n" +
                        "    }\n" +
                        "    }\n" +
                        "}\n";
            //设置请求体
            post.body(body);
            //请求
            HttpResponse execute = post.execute();
            //获得响应结果
            String json = execute.body();
//            System.out.println(json);
            //转成map
            Map map = JSONUtil.toBean(json, Map.class);
            int total=(int)((Map)((Map)map.get("hits")).get("total")).get("value");
            if(total>0)
            {
                List<Map> itemList=(List<Map>)((Map)map.get("hits")).get("hits");
                for(Map item:itemList)
                {
                    Map object= (Map) item.get("_source");
                    String traceId=(String) object.get("TRACE_ID");
                    String timestamp=(String) object.get("@timestamp");
                    String data=(String) object.get("DATA");
                    String _id=(String) item.get("_id");
                    String date=(String) object.get("DATE");
                    String localTime=(String) object.get("TIMESTAMP");
                    if(sampleType.equals("SAMPLE_FARE")&data.contains("限制大小=2048kb")) {
                        continue;
                    }
                    String filePath="D:\\test\\SAMPLE\\" +sampleType+ File.separator;
                    String fileName= dep + "_" + arr + "_" + date + "_"+localTime.replace(" ","T").replaceAll(":","M")+"_" + traceId + ".txt";
                    FileUtil.mkdir(filePath);
                    FileUtil.writeBytes(data.getBytes(),   filePath+ fileName);
                    result=true;
                }
            }
            return result;
    }
}
